package com.hspedu.Writer;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @Author Stringzhua
 * @Date 2024/3/16 18:07
 * description:
 */
public class FileWriter_ {
    public static void main(String[] args) {
        String filePath = "e:\\qiyeke\\filecontroller\\note.txt";
        //创建FileWriter对象
        FileWriter fileWriter = null;
        char[] chars={'a','b','c'};

        try {
            fileWriter = new FileWriter(filePath);
            //1.write(int):写入单个字符
            fileWriter.write('H');
            //2.write(char []):写入指定数组
            fileWriter.write(chars);
            //3.write(char[],off,len):写入指定数组的指定部分
            fileWriter.write("爪爪吃蒸饺".toCharArray(),0,3);
            //4.write(string):写入整个字符串
            fileWriter.write("爪爪玩游戏");
            fileWriter.write("风雨之后，定见彩虹");
            //5.write(string,off,len):写入字符串的指定部分
            fileWriter.write("上海北京洛阳杭州",0,2);//上海

            //数据量大的情况下,可以使用循环操作

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //对于FileWriter一定要关闭,或者flush才能真正把数据写入到文件
            //查看源码
            /*
            private void writeBytes() throws IOException {
            this.bb.flip();
            int var1 = this.bb.limit();
            int var2 = this.bb.position();

            assert var2 <= var1;

            int var3 = var2 <= var1 ? var1 - var2 : 0;
            if (var3 > 0) {
                if (this.ch != null) {
                assert this.ch.write(this.bb) == var3 : var3;
                } else {
                this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);
                }
            }

                this.bb.clear();
           }
            * */
            try {
//                fileWriter.flush();
                //关闭文件流,等价flush()+关闭
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("程序结束");
    }
}
